package com.sophialex.health.record.views;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.util.DateUtil;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;

import com.sophialex.health.common.platform.SuperContext;
import com.sophialex.health.person.vo.HrPerson;
import com.sophialex.health.person.vo.SoapService;
import com.sophialex.health.record.Activator;
import com.sophialex.health.record.action.OpenSoapServiceAction;
import com.sophialex.health.record.common.SOAPServiceDispath;
import com.sophialex.health.record.common.util.DataSource;
import com.sophialex.health.record.common.util.EventType;
import com.sophialex.health.record.common.util.HealthRecordListenerRegister;
import com.sophialex.health.record.common.utils.CommonUtils;
import com.sophialex.health.system.frame.resource.RcpResourceManager;

public class PersonBottomRightView extends ViewPart implements IPropertyChangeListener{

	public static final String ID = "com.sophialex.health.record.views.PersonBottomRightView"; //$NON-NLS-1$

	private Composite composite;

	private Action openSoapServiceAction;

	private List<SoapService> soapServiceList;
    
	private TreeViewer viewer;
	public PersonBottomRightView() {
	}

	/**
	 * Create contents of the view part.
	 * 
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		Composite container = new Composite(parent, SWT.NONE);
		container.setLayout(new FillLayout(SWT.HORIZONTAL));
		{

			{

				viewer = new TreeViewer(container, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
				DrillDownAdapter drillDownAdapter = new DrillDownAdapter(viewer);
				viewer.setContentProvider(new ViewContentProvider());
				viewer.setLabelProvider(new ViewLabelProvider());
				viewer.setSorter(new NameSorter());
				viewer.setInput(getViewSite());
				viewer.expandToLevel(2);
//				viewer.addSelectionChangedListener(new ISelectionChangedListener() {
//					public void selectionChanged(SelectionChangedEvent event) {
//						if(event.getSelection().isEmpty()) {
//							return;
//						}
//
//						if(event.getSelection() instanceof IStructuredSelection) {
//							IStructuredSelection selection = (IStructuredSelection) event.getSelection();
//							for(Iterator iterator = selection.iterator(); iterator.hasNext();) {
//								Object element = iterator.next();
//								if(element instanceof TreeObject) {
//                                       TreeObject treeObject = (TreeObject) element;
//                                       if(treeObject.getBusType().longValue() == 1){
//                                    	   System.out.println(treeObject.getName());
//                                       }
//                                       
//								}
//
//							}
//
//						}
//
//					}
//				});
			}

		}
		createActions();
		initializeToolBar();
		initializeMenu();
	
		HealthRecordListenerRegister.getInstance().addPropertyChangeListener(this);
	}

	private void initData() {
		HrPerson currentPerson = SuperContext.currentPerson;
		if(currentPerson!=null){
			soapServiceList = DataSource.soapService.getSoapServiceByPerosnId(currentPerson.getId());
		}else{
			soapServiceList = null;
		}
		
	}

	private void createActions() {
		
		openSoapServiceAction = new OpenSoapServiceAction(getSite().getWorkbenchWindow(),viewer);
	}
	/**
	 * Initialize the toolbar.
	 */
	private void initializeToolBar() {
		IToolBarManager toolbarManager = getViewSite().getActionBars().getToolBarManager();
		contributeToActionBars();
	}

	/**
	 * Initialize the menu.
	 */
	private void initializeMenu() {
		IMenuManager menuManager = getViewSite().getActionBars().getMenuManager();
	}
	
	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalToolBar(bars.getToolBarManager());
	}
	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(openSoapServiceAction);
	}

	@Override
	public void setFocus() {
		// Set the focus
	}

	public class TreeObject implements IAdaptable {
		private String name;

		private SoapService soapService;

		private TreeParent parent;

		private Long busType;

		public Long getBusType() {
			return busType;
		}

		public void setBusType(Long busType) {
			this.busType = busType;
		}

		public TreeObject(String name) {
			this.name = name;
		}

		public String getName() {
			return name;
		}

		public SoapService getSoapService() {
			return soapService;
		}

		public void setSoapService(SoapService soapService) {
			this.soapService = soapService;
		}

		public void setParent(TreeParent parent) {
			this.parent = parent;
		}

		public TreeParent getParent() {
			return parent;
		}

		public String toString() {
			return getName();
		}

		public Object getAdapter(Class key) {
			return null;
		}
	}

	public class TreeParent extends TreeObject {
		private ArrayList children;

		public TreeParent(String name) {
			super(name);
			children = new ArrayList();
		}

		public void addChild(TreeObject child) {
			children.add(child);
			child.setParent(this);
		}

		public void removeChild(TreeObject child) {
			children.remove(child);
			child.setParent(null);
		}

		public TreeObject[] getChildren() {
			return (TreeObject[]) children.toArray(new TreeObject[children.size()]);
		}

		public boolean hasChildren() {
			return children.size() > 0;
		}
	}

	class ViewContentProvider implements IStructuredContentProvider, ITreeContentProvider {
		private TreeParent invisibleRoot;

		public void inputChanged(Viewer v, Object oldInput, Object newInput) {
		}

		public void dispose() {
		}

		public Object[] getElements(Object parent) {
			if(parent.equals(getViewSite())) {
				if(invisibleRoot == null)
					initialize();
				return getChildren(invisibleRoot);
			}
			return getChildren(parent);
		}

		public Object getParent(Object child) {
			if(child instanceof TreeObject) {
				return ((TreeObject) child).getParent();
			}
			return null;
		}

		public Object[] getChildren(Object parent) {
			if(parent instanceof TreeParent) {
				return ((TreeParent) parent).getChildren();
			}
			return new Object[0];
		}

		public boolean hasChildren(Object parent) {
			if(parent instanceof TreeParent)
				return ((TreeParent) parent).hasChildren();
			return false;
		}

		public void initialize() {
			initData();
			TreeParent root = new TreeParent("所有服务记录");
			if(soapServiceList != null) {
				Map<Long, List<Long>> map = CommonUtils.getBusTypeGroup(CommonUtils.getBusTypes(soapServiceList));
				if(map != null && !map.isEmpty()) {
					int i = 1;
					for(Iterator it = map.keySet().iterator(); it.hasNext();) {
						Long sub = (Long) it.next();
						List<Long> list = map.get(sub);

						String big_title = CommonUtils.getBusTypeName(sub);
						TreeParent tparent = new TreeParent(big_title);
						root.addChild(tparent);

						if(list != null && list.size() > 0) {
							for(int j = 0; j < list.size(); j++) {
								Long sub2 = list.get(j);
								int k = 0;
								int count = 0;
								List<TreeObject> treeList = new ArrayList<TreeObject>();
								for(Iterator ite = soapServiceList.iterator(); ite.hasNext();) {
									SoapService service = (SoapService) ite.next();
									if(sub2.equals(service.getBusType())) {
										SOAPServiceDispath.serviceMap.get(service.getBusType());
										String serviceTime = DateUtil.formatDate(service.getServiceTime(), "yyyy-MM-dd");
										TreeObject t = new TreeObject(serviceTime);
										t.setSoapService(service);
										t.setBusType(1l);
										treeList.add(t);
										count++;
										k++;
									}
								}
								String serviceName = CommonUtils.getBusTypeName(sub2) + " （" + count + "）";
								TreeParent sparent = new TreeParent(serviceName);
								sparent.setBusType(0l);
								tparent.addChild(sparent);
								tparent.setBusType(sub);
								for(int l = 0; l < treeList.size(); l++) {
									sparent.addChild(treeList.get(l));
								}
							}
						}
						i++;
					}
				}
			}

			invisibleRoot = new TreeParent("");
			invisibleRoot.addChild(root);
		}
	}

	class ViewLabelProvider extends LabelProvider {

		public String getText(Object obj) {
			return obj.toString();
		}

		public Image getImage(Object obj) {
			String imageKey = ISharedImages.IMG_OBJ_ELEMENT;
			if(obj instanceof TreeParent) {
				TreeParent o = (TreeParent) obj;
				if(o.getBusType() == null) {
					imageKey = "icons/view/addCate.png";
				} else if(o.getBusType().longValue() == 0) {
					imageKey = "icons/view/brzl.png";
				} else {
					imageKey = "icons/view/" + o.getBusType() + ".png";
				}
				return RcpResourceManager.getPluginImage(Activator.getDefault(), imageKey);
			}

			return RcpResourceManager.getPluginImage(Activator.getDefault(), "icons/view/yzxx.png");

		}
	}

	class NameSorter extends ViewerSorter {}


	public void propertyChange(PropertyChangeEvent event) {
		if(event.getProperty().equals(EventType.REFRESH)){
		    initData();
			viewer.setContentProvider(new ViewContentProvider());
			viewer.setLabelProvider(new ViewLabelProvider());
			viewer.setSorter(new NameSorter());
			viewer.setInput(getViewSite());
			viewer.expandToLevel(2);
		}
		if(event.getProperty().equals(EventType.REFRESH_ONLY)){
		    initData();
			viewer.setContentProvider(new ViewContentProvider());
			viewer.setLabelProvider(new ViewLabelProvider());
			viewer.setSorter(new NameSorter());
			viewer.setInput(getViewSite());
			viewer.expandToLevel(2);
		}
	}

}
